# -*- coding:utf-8 -*-
from flask import Flask
from config import LOG_DIR, APP_DIR
from .extensions import db, lm, exceptional, cache, csrf, mymail, theme, migrate
from .errors import config_error_handles
from .apphandles import config_request_handles
from .appprocessor import config_context_processor
from .helpers import register_blueprints
from celery import Celery
import config
import os
#: loginmanager 设置
def setloginmanager(app):
    from models import AnonymousUser

    lm.init_app(app)
    lm.anonymous_user = AnonymousUser
    lm.session_protection = 'strong'
    lm.login_view = 'user.login'
    lm.login_message = u"请先登录"
    return lm


#: 设置日志
def setlog(app):
    if not app.debug:
        import logging
        from logging.handlers import RotatingFileHandler

        file_handler = RotatingFileHandler(LOG_DIR + '/golsee.log', 'a', 1 * 1024 * 1024, 10)
        file_handler.setFormatter(
            logging.Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]'))
        app.logger.setLevel(logging.INFO)
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)
        app.logger.info('golsee startup')


# ; 创建APP
def createapp(register_blueprint=True):
    app = Flask(__name__)
    app.config.from_object(config)
    db.init_app(app)
    cache.init_app(app)
    migrate.init_app(app, db)
    if app.config['DEBUG'] is False:
        exceptional.init_app(app)
    if register_blueprint is True:
        csrf.init_app(app)
        mymail.init_app(app)
        setloginmanager(app)
        config_context_processor(app)
        register_blueprints(app, 'golsee', [os.path.dirname(__file__)])
        config_request_handles(app)
        config_error_handles(app)
        theme.init_themes(app, app_identifier='golsee')
    setlog(app)
    return app


def celeryapp(app=None):
    app = app or createapp(register_blueprint=False)
    celery = Celery(app.name, broker=app.config['CELERY_BROKER_URL'])
    celery.conf.update(app.config)
    TaskBase = celery.Task

    class ContextTask(TaskBase):
        abstract = True

        def __call__(self, *args, **kwargs):
            with app.app_context():
                return TaskBase.__call__(self, *args, **kwargs)

    celery.Task = ContextTask
    return celery
